var app = sm("do_App");
var page = sm("do_Page");
var rootview = ui("$");
var nf = sm("do_Notification");
var hashdata = mm("do_HashData");
var mallUrl = require("url/mall");
var userUrl = require("url/user");
var couponUrl = require("url/coupon");
var qqHttp = require("helper/http");
var orderHelper = require("helper/order");
var httpSilence = require("helper/httpSilence");
var qqmath = require("util/qqmath");

var do_LinearLayout_item = ui("do_LinearLayout_item");
var do_Button_order = ui("do_Button_order");
var do_ALayout_address = ui("do_ALayout_address");
var do_Label_address = ui("do_Label_address");
var do_TextField_remark = ui("do_TextField_remark");
var do_Label_sales = ui("do_Label_sales");
var do_Label_freight = ui("do_Label_freight");
//var do_Label_delivery = ui("do_Label_12");
var deliveryAout = ui("deliveryAout");
var helperOpen = require("helper/open");
var listview = ui("do_ListView");
var listdata = mm("do_ListData");
var nf = sm("do_Notification");
listview.bindItems(listdata);
var noData = [{"template":1}];

//选择配送类型
var deliveryAout01 = ui("deliveryAout01");
var deliveryAout02 = ui("deliveryAout02");
var deliveryAout03 = ui("deliveryAout03");
var deliveryAoutImg01 = ui("deliveryAoutImg01");
var deliveryAoutImg02 = ui("deliveryAoutImg02");
var deliveryAoutImg03 = ui("deliveryAoutImg03");

var param = {};
var selectItems = [];
var selectId;
var totalPriceLabel = ui("totalPriceLabel");
var sendDeliveryType;
//促销
var requirement = 0;
var subsidy = 0;
var salesName="";
//店铺配送起送金额
var freeDeliverValue = 0.00;
//店铺配送运费
var shopFreight = 0.00;
//社区店铺圈圈配送起送金额
var quanDeliverValue = 0.00;
//社区店铺圈圈配送运费
var quanFreight = 0.00;
//实际的配送费用
var freight = 0.00;

//配送方式：1-买家自提；2-店铺配送；3-圈圈配送
var deliveryType = 1;
//起送金额提示信息
var deliveryMsg = "";
//andriod返回键
var shopId;
var style;
page.on("back", function() {
    app.closePage({"cart_toOrder":true});
});

page.on("result", function(data) {
	if (data) {
		if (data.nextAddr || data.houseNumber) {
			do_Label_address.text = data.contactName + " " + data.address;
			param.addressId = data.id;
			selectId = data.id;
		}
	}
});

/* 头部 */
var headerAout = ui("do_ALayout_header");
var addheader = headerAout.add("header", "source://view/reuse/header.ui", 0, 0);
var header = ui("header");
//左上角-返回
var headerLeft = ui(addheader+".headerLeft");
var labelTitle = ui(addheader+".labelTitle");
labelTitle.text = "提交订单";
headerLeft.on("touch", function() {
    app.closePage({"cart_toOrder":true})
});

page.on("loaded", function(){
	//读取当前页面的传入参数
	var data = page.getData();
	style=data.style;
	init(data);
});

var totalPrice=0.00;
var couponUserIds;
var totalMinu=0.00;
var isOutsideCouponUser=false;
var isInsideCouponUser=false;
function init(data) {
	//读取当前页面传入的参数 
	shopId = data.shopId;
	//获取默认地址
	qqHttp.post(userUrl.url.address.getDefault, {}, function(data) {
		if (data && data.userAddress) {
			var userAddress = data.userAddress;
			do_Label_address.text = userAddress.contactName + " " + userAddress.address;
			param.addressId = userAddress.id;
			selectId = userAddress.id;
		}
	});
	
	if(data.fromPage && data.fromPage == "shop_index"){
		//店铺首页立即购买按钮
		qqHttp.post(mallUrl.url.cart.indexByShop, {shopId:shopId}, function(data) {
			if (data && data.list && data.list.length > 0) {
				cartList = data.list;
				for(var i=0; i<data.list.length; i++){
					var item = {};
					item.productId = cartList[i].productSpecId; //商品规格
					item.quantity = cartList[i].quantity;
					item.img = cartList[i].img;
					item.name = cartList[i].name;
					item.spec = cartList[i].spec;
					item.price = cartList[i].price;
					item.marketPrice = cartList[i].marketPrice;
					selectItems.push(item);
				}
				
				listdata.addData(selectItems);
				totalPrice = qqmath.getDight(data.cartTotalPrice,2);
				totalPriceLabel.text = totalPrice+'';
				getDisParam(shopId);
			}else{
				app.closePage({"cart_toOrder":true});
			}
			listview.refreshItems();
		});
	}else{
		selectItems = data.addItems;
		totalPrice = qqmath.getDight(data.total,2);	
		if(selectItems.length){
			listdata.addData(selectItems);
		}else{
			listdata.addData(noData);
		}
		totalPriceLabel.text = totalPrice+'';
		getDisParam(shopId);
		listview.refreshItems();
	}
	
}

function getDisParam(shopId){
	//获取店铺配送、促销活动参数
	httpSilence.post(mallUrl.url.order.getDisParam, {'id':shopId}, function(data) {
		if(data && data.freeDeliverValue && data.sendDeliveryType){
			freeDeliverValue = data.freeDeliverValue;
			if(deliveryType == 1){
				deliveryType = 9999;
				sendDeliveryTypeStr = data.sendDeliveryType;
				var sendDeliveryTypeArray = sendDeliveryTypeStr.split(";");
				for(var i in sendDeliveryTypeArray){
					if(sendDeliveryTypeArray[i] == 1){//自提
						deliveryAout03.visible = true;
					}else if(sendDeliveryTypeArray[i] == 2){//店家配送
						deliveryAout01.visible = true;
						shopFreight = data.freight;
					}else if(sendDeliveryTypeArray[i] == 3){//圈圈配送
						deliveryAout02.visible = true;
						if(data.quanDeliverValue){//圈圈配送起送金额
							quanDeliverValue = data.quanDeliverValue;
							quanFreight = data.quanFreight
						}
					}
				}
				deliveryAout.redraw();
				if(sendDeliveryTypeArray.length > 1){
					if (sendDeliveryTypeStr.indexOf("2") != -1 || sendDeliveryTypeStr.indexOf("3") != -1) {
						checkFreeDeliver(freeDeliverValue);//校验交易金额是否满足店铺配送起送金额
					}
				}else if(sendDeliveryTypeArray.length == 1){
					if(sendDeliveryTypeArray[0] == 3){
						checkFreeDeliver(quanDeliverValue);//校验交易金额是否满足圈圈配送起送金额
					}
				}
				
			}
		}else{
			deliveryMsg = "店铺配送参数错误";
		}
		
		//促销-满减活动 加上运费来算
		if(data && data.sales){
			requirement = data.sales.requirement;
			subsidy = data.sales.subsidy;
			salesName = data.sales.name;
			if(totalPrice >= requirement){
				var temp = qqmath.getDight(totalPrice-subsidy,2);
				if(temp >= 0){
					totalPriceLabel.text = temp+'';
					do_Label_sales.text="("+salesName+")";
				}else{
					nf.toast("活动信息错误");
					totalPriceLabel.text = totalPrice+'';
				}
			}else{
				totalPriceLabel.text = totalPrice+'';
			}
		}else{
			totalPriceLabel.text =totalPrice+'';
		}
		myCouponList();
	});
}

function checkFreeDeliver(freeDeliverValue){
	//判断是否满足起送金额
	var totalPrice = 0.00;
	for(var i=0; i < selectItems.length; i++){
		totalPrice = totalPrice + parseFloat(selectItems[i].price) * parseInt(selectItems[i].quantity);
	}
	var total = parseFloat(totalPrice);
	if(total < freeDeliverValue){
		do_Button_order.bgColor = "949EAAFF";
		deliveryMsg = "商品总价满"+freeDeliverValue+"元起送";
	}else{
		do_Button_order.bgColor = "FF7F00FF";
		deliveryMsg = "";
	}
	if(freight > 0){
		do_Label_freight.text = "(另需配送费￥"+freight+")";
	}else{
		do_Label_freight.text = "免配送费";
	}
}

//选择地址
do_ALayout_address.on("touch", function() {
	helperOpen.open("source://view/user/userAddress/list.ui",{select:true,selectId:selectId});
});

var radioItem = [deliveryAoutImg01,deliveryAoutImg02, deliveryAoutImg03];
deliveryAout01.on("touch",function(data,e){
	do_Label_freight.text = "";
	checkRadio(0);
	deliveryType = 2;//店家配送
	freight = shopFreight;
	checkFreeDeliver(freeDeliverValue);//校验各商家交易金额是否满足起送金额
});
deliveryAout02.on("touch",function(data,e){
	do_Label_freight.text = "";
	checkRadio(1);
	deliveryType = 3;//圈圈配送
	freight = quanFreight;
	checkFreeDeliver(quanDeliverValue);//校验各商家交易金额是否满足起送金额
});
deliveryAout03.on("touch",function(data,e){
	do_Label_freight.text = "";
	checkRadio(2);
	deliveryType = 1;//买家自提
	deliveryMsg = ""
	do_Button_order.bgColor = "FF7F00FF";
});
function checkRadio(index){
	for (var i = 0; i < radioItem.length; i++) {
		if(i==index){
			radioItem[i].source="source://image/common/radiocheck.png";
		}else{
			radioItem[i].source="source://image/common/radio.png";
		}
	}
}

do_Button_order.on("touch", '',1000,function(data, e){
	if(deliveryType == 9999){
		nf.toast("请选择配送方式");
		return;
	}
	if(deliveryMsg != ""){
		nf.toast(deliveryMsg);
		return;
	}
	var orderItems = [];
	for (var i=0; i<selectItems.length; i++) {
		var orderItem = {"productId":"","quntity":""};
		orderItem.productId = selectItems[i].productId;
		orderItem.quntity = selectItems[i].quantity;
		orderItems.push(orderItem);
	}
	param.orderItems = orderItems;
	param.remark = do_TextField_remark.text;
	param.deliveryType = deliveryType;
	param.orderType = orderHelper.type.QSHOP;
	param.shopId = shopId;//店铺ID
	if(deliveryType != 1){
		if(!selectId){
			nf.toast("请选择收货地址");
			return;
		}
		qqHttp.post(mallUrl.url.order.doAdd, param, function(data) {
			nf.toast("下单成功");
			if(data.zeroFlag && data.zeroFlag !== "undefined" && data.zeroFlag == "1"){
				helperOpen.openBuyerOrder(data.orderNo);
			}else{
				orderHelper.toPay(data.orderNo);
			}
		});
	}else if(deliveryType == 1){
		qqHttp.post(mallUrl.url.order.doAdd, param, function(data) {
			nf.toast("下单成功");
			if(data.zeroFlag && data.zeroFlag !== "undefined" && data.zeroFlag == "1"){
				helperOpen.openBuyerOrder(data.orderNo);
			}else{
				orderHelper.toPay(data.orderNo);
			}
		});
	}
});
function myCouponList(){
	for (var i=0; i<selectItems.length; i++) {
			selectItems[i].quntity = selectItems[i].quantity;
			selectItems[i].supplierType=2;
		}
		var params = {
			orderItems:selectItems,
			style:style
		};
		httpSilence.post(couponUrl.url.user.qmallCoupon, params, function(data) {
			for (var i = 0; i < data.myCoupon.length; i++) {
				data.myCoupon[i].template=2;
			}
			totalMinu=data.totalMinu;
			param.orderCouponList=data.orderCouponList;
			param.totalMinu=totalMinu;
			totalPriceLabel.text =qqmath.getDight(totalPriceLabel.text-totalMinu,2)+'';
			listdata.addData(data.myCoupon);
			listview.refreshItems();
		});
}
function fD(a, b, c) {
	for (; a > c;)
		a -= c - b;
	for (; a < b;)
		a += c - b;
	return a;
};
function jD(a, b, c) {
	b != null && (a = Math.max(a, b));
	c != null && (a = Math.min(a, c));
	return a;
};
function yk(a) {
	return Math.PI * a / 180
};
function Ce(a, b, c, d) {
	var dO = 6370996.81;
	return dO * Math.acos(Math.sin(c) * Math.sin(d) + Math.cos(c) * Math.cos(d) * Math.cos(b - a));
};
function getDistance(a, b) {
	if (!a || !b)
		return 0;
	a.lng = fD(a.lng, -180, 180);
	a.lat = jD(a.lat, -74, 74);
	b.lng = fD(b.lng, -180, 180);
	b.lat = jD(b.lat, -74, 74);
	return Ce(yk(a.lng), yk(b.lng), yk(a.lat), yk(b.lat));
};